import React, { useState, useMemo, useEffect, useCallback } from 'react'
import { Divider, Empty, Input, Select, Tag } from 'antd';
import './style.less'
import { ResultHeader } from "@/components/DataFlow/common/ResultHeader";
import { useCurrentNode } from "@/hooks/useCurrentNode";
import { useNodesData, useReactFlow } from "@xyflow/react";
import { RESULT_SHOW_MODE_DICT } from "@/constant/icons";
import { usePreviousNodes } from "@/hooks/usePreviousNodes";
import { UnionResultData } from './UnionResultData';
import { UnionFieldResult } from './UnionFieldResult';
import { AnimatePresence, motion } from 'motion/react';
import { pick } from 'lodash-es';

export const Union = () => {
  const currentNode = useCurrentNode()
  const nodeData = useNodesData(currentNode?.id)
  const { updateNodeData } = useReactFlow()
  const [searchValue, setSearchValue] = useState('')
  const [showMode, setShowMode] = useState(RESULT_SHOW_MODE_DICT.field)
  const preNodes = usePreviousNodes(currentNode?.id)

  const relations = nodeData?.data?.relations ?? []
  const columns = nodeData?.data?.columns ?? []

  const dataSource = useMemo(() => {
    return columns?.map((item, idx) => {
      return {
        ...item,
        relations: relations?.[idx]
      }
    })
  }, [columns, relations])

  //表格数据源
  const getInitialDataSource = useCallback(() => {
    const columnGroups = preNodes?.reduce((acc, curNode) => {
      curNode?.data?.columns?.forEach(column => {
        const columnName = column.columnName
        if (!acc[columnName]) {
          acc[columnName] = {
            ...column,
            relations: []
          }
        }
        acc[columnName].relations.push({
          sourceNodeId: curNode.id,
          ...column
        })
      })
      return acc
    }, {})
    // 转换为最终数据结构
    return Object.values(columnGroups).map(group => ({
      ...group
    }));
  }, [preNodes]);


  const selectedRowKeys = useMemo(() => {
    return columns?.map(c => c?.columnId) || []
  }, [columns])

  // 修复5：优化选择处理
  const handleSelectionChange = useCallback((items) => {
    const finalColumns = dataSource?.filter(
      col => items.includes(col.columnId))

    updateNodeData(currentNode?.id, {
      columns: finalColumns
    })
  }, [dataSource, updateNodeData])

  useEffect(() => {
    if (nodeData?.data && !nodeData.data.columns) {
      const ds = getInitialDataSource()
      const columns = ds?.map((item) => pick(item, ['columnId', 'columnName', 'columnType', 'columnComment'])) || []
      const relationMap = ds?.reduce((acc, item) => {
        preNodes?.forEach((node) => {
          if (!acc[node.id]) {
            acc[node.id] = []
          }
          const relation = item.relations?.find(r => r.sourceNodeId === node.id)
          acc[node.id]?.push({
            columnId: relation?.columnId || null,
            columnName: relation?.columnName || null,
            columnType: relation?.columnType || null,
            columnComment: relation?.columnComment || null,
          })
        })
        return acc
      }, {}) || {}
      const relations = Object.keys(relationMap).map((sourceNodeId) => {
        return {
          sourceNodeId,
          sourceColumns: relationMap[sourceNodeId]
        }
      })
      updateNodeData(currentNode?.id, { columns, relations })
    }
  }, [])

  // 修复7：优化动态列生成
  // 补充下拉选择处理逻辑
  const dynamicColumns = useMemo(() => {
    return preNodes?.map((node) => {
      const opts = node?.data?.columns?.map((c) => ({
        label: c.columnName,
        value: c.columnId,
        _meta: c
      })) || [];
      return {
        title: node?.data?.label,
        key: node?.id,
        dataIndex: node?.id,
        renderFormItem: ({ index }, { record }) => {
          const curVal = relations?.find(r => r?.sourceNodeId === node.id)?.sourceColumns?.[index]?.columnId
          return (
            <Select
              optionFilterProp="label"
              options={opts}
              value={curVal}
              defaultValue={curVal}
              placeholder="请选择"
              allowClear
              onChange={(value, option) => {
                const meta = option?._meta ?? {
                  columnId: null,
                  columnName: null,
                  columnType: null,
                  columnComment: null
                };
                const newRelations = relations?.map((relation) => {
                  if (relation?.sourceNodeId === node.id) {
                    return {
                      ...relation,
                      sourceColumns: relation.sourceColumns?.map((col) => {
                        if (col.columnId === curVal) {
                          return {
                            ...col,
                            ...meta
                          }
                        } else {
                          return col
                        }
                      })
                    }
                  }else {
                    return relation
                  }
                })
                updateNodeData(currentNode?.id, { relations: newRelations })
              }}
            />
          );
        }
      }
    }) || [];
  }, [preNodes, dataSource, columns]);

  // 修改字段名处理逻辑
  const handleChange = useCallback((records) => {
    console.log('handleChange', records)
  }, [updateNodeData]);

  const fieldColumns = useMemo(() => [
    {
      title: '序号',
      editable: false,
      width: 50,
      render: (_, record, idx) => <div style={{ direction: 'rtl' }}>{idx + 1}</div>
    },
    {
      title: '合并后字段名',
      dataIndex: 'columnName',
      key: 'columnName',
      formItemProps: (form, config) => {
        return {
          rules: [
            {
              required: true,
              message: '该项为必填项'
            },
            {
              validator: async (_, value) => {
                if (value && dataSource?.some(ds => ds.columnName === value)) {
                  return Promise.reject(new Error('字段名已存在，请重新输入'));
                }
                return Promise.resolve();
              }
            }
          ]
        }
      },
      renderFormItem: (_, { record }, form) => {
        const handleChange = ({ target }) => {
          if (!target?.value) return
          const newColumns = columns?.map(ds => {
            if (ds.columnId === record.columnId) {
              return {
                ...ds,
                columnName: target?.value
              }
            }
            return ds
          })
          updateNodeData(currentNode?.id, { columns: newColumns })
        }
        return <Input value={record?.columnName} allowClear placeholder='请输入' onChange={handleChange} />
      }
    },
    ...dynamicColumns,
    {
      title: '操作',
      valueType: 'option',
      width: 80
    }
  ], [dynamicColumns])


  const renderContent = () => {
    if (!preNodes?.length) {
      return (
        <motion.div
          key="empty"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.2 }}
        >
          <Empty description="请先连接上游节点" />
        </motion.div>
      );
    }

    switch (showMode) {
      case RESULT_SHOW_MODE_DICT.data:
        return (
          <motion.div
            key="data"
            initial={{ opacity: 0, x: 10 }}
            animate={{ opacity: 1, x: 0 }}
            exit={{ opacity: 0, x: -10 }}
            transition={{ duration: 0.2 }}
          >
            <UnionResultData columns={columns} />
          </motion.div>
        );
      case RESULT_SHOW_MODE_DICT.field:
        return (
          <motion.div
            key="field"
            initial={{ opacity: 0, x: 10 }}
            animate={{ opacity: 1, x: 0 }}
            exit={{ opacity: 0, x: -10 }}
            transition={{ duration: 0.2 }}
          >
            <UnionFieldResult
              datasource={dataSource}
              selectedRowKeys={selectedRowKeys}
              onSelectionChange={handleSelectionChange}
              onChange={handleChange}
              columns={fieldColumns}
            />
          </motion.div>
        );
      default:
        return (
          <motion.div
            key="default-empty"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.2 }}
          >
            <Empty />
          </motion.div>
        );
    }
  };

  return (
    <div className="union-result-container">
      <ResultHeader
        info="合并结果"
        total={dataSource.length}
        select={columns.length}
        mode={showMode}
        onChange={setShowMode}
        onSearch={setSearchValue}
      />
      <Divider style={{ margin: '8px 0' }} />
      <div className="union-result-table">
        <AnimatePresence mode="wait">
          {renderContent()}
        </AnimatePresence>
      </div>
    </div>
  );
}
